package io.renren.common.utils;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

@Slf4j
public class StatusSocket extends Thread {

    /*private static int PORT = Integer.valueOf(ConfigVariable.STATUS_PORT);*/
    @Override
    public void run() {
        try {
            ServerSocket serverSocket = buildServerSocket();
            serverSocket.setSoTimeout(20000);
            Thread.sleep(2000);
            log.info("开启天线实时推送服务:");
            while (!Thread.currentThread().isInterrupted()) {
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                    socket.setKeepAlive(true);
                } catch (SocketTimeoutException e) {
                    serverSocket.close();
                    serverSocket = buildServerSocket();
                    continue;
                }
                new ReceiveSocket(socket).start();
                new SendSocket(socket).start();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 数据推送线程
     */
    class SendSocket extends Thread {
        private Socket socket;

        SendSocket(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            BufferedWriter writer = null;
            OutputStreamWriter osw = null;

            try {
                osw = new OutputStreamWriter(socket.getOutputStream());
                writer = new BufferedWriter(osw);
                while (socket.getKeepAlive()) {
                    //这里放入需要传输的数据 str
                    String str = "";
                    //BufferedReader的readLine方法是按行读取，末尾加上\n方便对方读取
                    writer.write(str + "\n");
                    writer.flush();
                    Thread.sleep(1500);
                }
            } catch (Exception e) {
                /*continue;*/
            } finally {
                try {
                    writer.close();
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 请求回复线程
     */
    class ReceiveSocket extends Thread {
        private Socket socket;

        ReceiveSocket(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            //BufferedReader reader = null;
            //InputStreamReader isr = null;
            InputStream in = null;
            try {
                in = socket.getInputStream();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            ;
            BufferedWriter writer = null;
            OutputStreamWriter osw = null;

            try {
                //isr = new InputStreamReader(socket.getInputStream());
                //reader = new BufferedReader(isr);
                osw = new OutputStreamWriter(socket.getOutputStream());
                writer = new BufferedWriter(osw);
                //while(null != (readStr = reader.readLine())){
                byte[] buffer = new byte[1024];
                while (in.read(buffer) > 0) {
                    String readStr = new String(buffer);
                    JSONObject readJson = JSONObject.parseObject(readStr.trim());
                    if ("updateMsg".equals(readJson.getString("msgType"))) {
                        //做出处理
                        //。。。。
                        //处理成功后回复
                        String result = "ok";
                        writer.write(result.toString() + "\n");
                        writer.flush();
                    }
                }
            } catch (Exception e) {
                /*continue;*/
            } finally {
                try {
                    writer.close();
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /* 初始化socket */
    private ServerSocket buildServerSocket() throws IOException, SocketException {
        ServerSocket serverSocket = new ServerSocket(8989); // 端口号
        serverSocket.setSoTimeout(20000);
        return serverSocket;
    }
}

